<?php

namespace api\services\goods;

use api\extensions\ApiBaseService;
use common\models\goods\goods\GoodsCollectModel;
use api\services\goods\GoodsService;
/**
 * Desc 商品收藏管理服务类
 * @author WMX
 */
class GoodsCollectService extends ApiBaseService
{

    // 商品收藏-取消收藏
    public static function collect($params = [])
    {
        try {
            $user = self::getUser();
            $goods_collect = GoodsCollectModel::getDataOne(['and', ['=', 'user_id', $user['id']], ['=', 'gid', $params['id']]]);
            if (empty($goods_collect)) {
                GoodsCollectModel::create([
                    'gid' => $params['id'],
                    'user_id' => $user['id'],
                    'create_time' => date('Y-m-d H:i:s')
                ]);
            } else {
                GoodsCollectModel::deleteAll(['and', ['=', 'user_id', $user['id']], ['=', 'gid', $params['id']]]);
            }
            return self::jsonSuccess();
        } catch (\Exception $exc) {
            return self::jsonSuccess();
        }
    }

    // 获取商品收藏列表
    public static function getList($params)
    {
        try {
            $user = self::getUser();
            $collect_goods = GoodsCollectModel::getDataAll(['user_id' => $user['id']], $params['page'], 20, 'create_time desc', ['gid']);
            if (empty($collect_goods['list'])) {
                return self::jsonSuccess([]);
            }
            $goods = GoodsService::getGoodsInfo(array_column($collect_goods['list'], 'gid'), 1, 1);
            return self::jsonSuccess($goods);
        } catch (\Exception $exc) {
            return self::jsonSuccess();
        }
    }
}
